<!--
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-04-22 16:49:12
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-05 17:27:13
 * @FilePath: /vue3-admin/src/components/ui/CustomTags/CustomTags.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->

<script lang="ts" setup>
import { toRefs, ref, nextTick } from 'vue';
import { ElInput } from 'element-plus';
import { message } from '@/utils/message';

const props = defineProps<{
    modelValue: string[];
}>();

const emits = defineEmits<{
    (event: 'update:model-value', value: string[]): void;
}>();

const { modelValue } = toRefs(props);
const inputRef = ref<InstanceType<typeof ElInput>>();
const inputVisible = ref(false);
const inputValue = ref('');

const showInput = () => {
    inputVisible.value = true;
    nextTick(() => {
        inputRef.value!.input!.focus();
    });
};

const handleDel = (value: string) => {
    emits(
        'update:model-value',
        modelValue.value.filter((item) => item !== value)
    );
};

const handleInputConfirm = () => {
    if (inputValue.value) {
        if (modelValue.value.includes(inputValue.value)) {
            return message('标签已存在', 'warning');
        }
        emits('update:model-value', [...modelValue.value, inputValue.value]);
    }
    inputVisible.value = false;
    inputValue.value = '';
};
</script>

<template>
    <div class="custom-tags-container">
        <el-tag
            v-for="tag in modelValue"
            class="mr10"
            size="large"
            :key="tag"
            closable
            @close="() => handleDel(tag)"
        >
            {{ tag }}
        </el-tag>
        <el-input
            v-if="inputVisible"
            ref="inputRef"
            v-model="inputValue"
            style="width: 80px"
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
        />
        <el-button v-else class="button-new-tag" @click="showInput">
            + 添加标签
        </el-button>
    </div>
</template>
